<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '商品容器',
  },
}
</route>
<template>
  <PageLayout :navTitle="navTitle" :backRouteName="backRouteName">
    <scroll-view class="scrollArea" scroll-y>
      <view class="form-container">
        <wd-form ref="form" :model="myFormData">
          <wd-cell-group border:true>
            <view class="{ 'mt-14px': 0 == 0 }">
              <wd-input
                label-width="100px"
                v-model="myFormData['code']"
                :label="get4Label('容器编码')"
                name="code"
                prop="code"
                placeholder="请选择容器编码"
                :rules="[]"
                clearable
              />
            </view>
            <view class="{ 'mt-14px': 1 == 0 }">
              <wd-input
                label-width="100px"
                v-model="myFormData['name']"
                :label="get4Label('容器名称')"
                name="name"
                prop="name"
                placeholder="请选择容器名称"
                :rules="[]"
                clearable
              />
            </view>
            <view class="{ 'mt-14px': 0 == 0 }">
              <wd-input
                label-width="100px"
                v-model="myFormData['capacity']"
                :label="get4Label('容量')"
                name="capacity"
                prop="capacity"
                placeholder="请选择容量"
                :rules="[]"
                clearable
              />
            </view>
            <view class="{ 'mt-14px': 1 == 0 }">
              <wd-input
                label-width="100px"
                v-model="myFormData['weight']"
                :label="get4Label('重量')"
                name="weight"
                prop="weight"
                placeholder="请选择重量"
                :rules="[]"
                clearable
              />
            </view>
            <view class="{ 'mt-14px': 0 == 0 }">
              <wd-input
                label-width="100px"
                v-model="myFormData['capacityUnit']"
                :label="get4Label('容量单位【固定值为：毫升、升、kg】')"
                name="capacityUnit"
                prop="capacityUnit"
                placeholder="请选择容量单位【固定值为：毫升、升、kg】"
                :rules="[]"
                clearable
              />
            </view>
            <view class="{ 'mt-14px': 1 == 0 }">
              <wd-input
                label-width="100px"
                v-model="myFormData['weightUnit']"
                :label="get4Label('重量单位【固定值为：毫升、升、kg】')"
                name="weightUnit"
                prop="weightUnit"
                placeholder="请选择重量单位【固定值为：毫升、升、kg】"
                :rules="[]"
                clearable
              />
            </view>
            <view class="{ 'mt-14px': 0 == 0 }"></view>
          </wd-cell-group>
        </wd-form>
      </view>
    </scroll-view>
    <view class="footer">
      <wd-button :disabled="loading" block :loading="loading" @click="handleSubmit">提交</wd-button>
    </view>
  </PageLayout>
</template>

<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app'
import { http } from '@/utils/http'
import { useToast } from 'wot-design-uni'
import { useRouter } from '@/plugin/uni-mini-router'
import { ref, onMounted, computed, reactive } from 'vue'
import { duplicateCheck } from '@/service/api'
import { tblProductContainerApi } from '@/api/api'
defineOptions({
  name: 'TblProductContainerForm',
  options: {
    styleIsolation: 'shared',
  },
})
const toast = useToast()
const router = useRouter()
const form = ref(null)
// 定义响应式数据
const myFormData = reactive({})
const loading = ref(false)
const navTitle = ref('新增')
const dataId = ref('')
const backRouteName = ref('TblProductContainerList')
// 定义 initForm 方法
const initForm = (item) => {
  console.log('initForm item', item)
  if (item?.dataId) {
    dataId.value = item.dataId
    navTitle.value = item.dataId ? '编辑' : '新增'
    initData()
  }
}
// 初始化数据
const initData = () => {
  http.get(tblProductContainerApi.queryById, { id: dataId.value }).then((res) => {
    if (res.success) {
      const obj = res.result
      if (obj && typeof obj === 'object' && !Array.isArray(obj)) {
        Object.assign(myFormData, { ...obj })
      }
    } else {
      toast.error(res?.message || '表单加载失败！')
    }
  })
}
const handleSuccess = () => {
  uni.$emit('refreshList')
  router.back()
}
/**
 * 校验唯一
 * @param values
 * @returns {boolean}
 */
async function fieldCheck(values: any) {
  const onlyField = []
  for (const field of onlyField) {
    if (values[field]) {
      // 仅校验有值的字段
      const res: any = await duplicateCheck({
        tableName: 'tbl_product_container',
        fieldName: field, // 使用处理后的字段名
        fieldVal: values[field],
        dataId: values.id,
      })
      if (!res.success) {
        toast.warning(res.message)
        return true // 校验失败
      }
    }
  }
  return false // 校验通过
}
// 提交表单
const handleSubmit = async () => {
  // 判断字段必填和正则
  if (await fieldCheck(myFormData)) {
    return
  }
  const url = dataId.value ? tblProductContainerApi.edit : tblProductContainerApi.add
  form.value
    .validate()
    .then(({ valid, errors }) => {
      if (valid) {
        loading.value = true
        http.post(url, myFormData).then((res) => {
          loading.value = false
          if (res.success) {
            toast.success('保存成功')
            handleSuccess()
          } else {
            toast.error(res?.message || '表单保存失败！')
          }
        })
      }
    })
    .catch((error) => {
      console.log(error, 'error')
      loading.value = false
    })
}
// 标题
const get4Label = computed(() => {
  return (label) => {
    return label && label.length > 4 ? label.substring(0, 4) : label
  }
})

// 标题
const getFormSchema = computed(() => {
  return (dictTable, dictCode, dictText) => {
    return {
      dictCode,
      dictTable,
      dictText,
    }
  }
})
/**
 * 获取日期控件的扩展类型
 * @param picker
 * @returns {string}
 */
const getDateExtendType = (picker: string) => {
  const mapField = {
    month: 'year-month',
    year: 'year',
    quarter: 'quarter',
    week: 'week',
    day: 'date',
  }
  return picker && mapField[picker] ? mapField[picker] : 'date'
}
// 设置pop返回值
const setFieldsValue = (data) => {
  Object.assign(myFormData, { ...data })
}
// onLoad 生命周期钩子
onLoad((option) => {
  initForm(option)
})
</script>

<style lang="scss" scoped>
.footer {
  width: 100%;
  padding: 10px 20px;
  padding-bottom: calc(constant(safe-area-inset-bottom) + 10px);
  padding-bottom: calc(env(safe-area-inset-bottom) + 10px);
}
:deep(.wd-cell__label) {
  font-size: 14px;
  color: #444;
}
:deep(.wd-cell__value) {
  text-align: left;
}
</style>
